 package com.project.fiveCerealsSavoury.controller;

import java.io.Writer;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;

import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.project.fiveCerealsSavoury.domain.Order;
import com.project.fiveCerealsSavoury.domain.OrderState;
import com.project.fiveCerealsSavoury.domain.DeliveryDomain;
import com.project.fiveCerealsSavoury.domain.Goods;
import com.project.fiveCerealsSavoury.domain.LogisticsDomain;
import com.project.fiveCerealsSavoury.domain.ReportForms;
import com.project.fiveCerealsSavoury.domain.Trade;
import com.project.fiveCerealsSavoury.domain.TradeStatus;
import com.project.fiveCerealsSavoury.domain.Wages;
import com.project.fiveCerealsSavoury.exception.BizException;
import com.project.fiveCerealsSavoury.service.AdministratorService;
import com.project.fiveCerealsSavoury.service.DeliveryService;
import com.project.fiveCerealsSavoury.service.LogisticsService;
import com.project.fiveCerealsSavoury.service.OrderService;
import com.project.fiveCerealsSavoury.service.ReportFormsService;
import com.project.fiveCerealsSavoury.transfer.AdminCon;
import com.project.fiveCerealsSavoury.transfer.LogAdd;
import com.project.fiveCerealsSavoury.transfer.Page;
import com.project.fiveCerealsSavoury.transfer.UserPage;



@Controller
public class AdministratorController {

	@Autowired
	private AdministratorService administratorService;
	@Autowired
	private ReportFormsService reportFormsService;
	@Autowired
	private OrderService orderservice;
	@Autowired
	private DeliveryService deliveryService;
	@Autowired
	private LogisticsService logisticsService;
	
	@RequestMapping("/addLogistics.htm")
	public String addLogistics(@Valid @ModelAttribute("logAdd")LogAdd logAdd,Integer orderId,ModelMap map){
		List<DeliveryDomain> querys = deliveryService.querys();
		map.put("querys", querys);
		try {
			List<LogisticsDomain> queryIndent = logisticsService.queryIndent(orderId);
			if (queryIndent != null) {
				map.put("indent", queryIndent);
				map.put("orderId", orderId);
				return "/order/logisticsAdd";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/queryList.do?isQuery=true";
	}
	@RequestMapping("/addLogistics.do")
	public String addLog(@Valid @ModelAttribute("logAdd")LogAdd logAdd,BindingResult result,ModelMap map){
		if (result.hasErrors()) {
			return "redirect:/addLogistics.htm";
		}
		logAdd.setDeliveryTime(new Timestamp(new Date().getTime()));
		try {
			logisticsService.addLog(logAdd);
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/queryList.do?isQuery=true";
	}
	//查询交易记录
	@RequestMapping("/queryCompany.do")
	public String queryCompany(ModelMap map){
		try {
			List<Trade> company = administratorService.getCompany(TradeStatus.INTERIOR);
			if (company != null) {
				map.put("company", company);
			}
			return "/admin/trade";
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
	}
	@RequestMapping("/con.htm")
	public String con(@Valid @ModelAttribute("adminCon")AdminCon adminCon,ModelMap map){
		List<DeliveryDomain> querys = deliveryService.querys();
		map.put("querys", querys);
		return "order/addCon";
	}
	@RequestMapping("/con.do")
	public String consignment(@Valid @ModelAttribute("adminCon")AdminCon adminCon,BindingResult result,ModelMap map){
		if (result.hasErrors()) {
			return "redirect:/con.htm";
		}
		String math =adminCon.getDeliveryId()+(int) (1+Math.random()*(10000000-1))+adminCon.getOrderId()+"000";
		String waybillId =String.valueOf(math);
		try {
			boolean consignment = administratorService.consignment(adminCon.getOrderId(), adminCon.getDeliveryId(), adminCon.getStartAddress(),waybillId);
			if (consignment) {
				return "redirect:/queryList.do?isQuery=true";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/queryList.do?isQuery=true";
		
	}
	
	@RequestMapping("/dispose.do")
	public String dispose(Integer orderId,ModelMap map){
		try {
			boolean dispose = administratorService.dispose(orderId);
			if (dispose) {
				return "redirect:/queryList.do?isQuery=true";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/queryFinance.do?goon=true";
	}
	
	@RequestMapping(value="/addDelivery.htm",method=RequestMethod.GET)
	public String insert(@ModelAttribute("delivery") DeliveryDomain deliveryDomain){
		return "/admin/addDelivery";
	}
	@RequestMapping(value ="/addDelivery.do",method=RequestMethod.POST)
	public String add(@ModelAttribute("delivery") DeliveryDomain deliveryDomain){
		deliveryService.add(deliveryDomain);
		return "redirect:/admin.do";
	}
	//进入产品管理
	@RequestMapping("/ckgl.do")
	public String index(){
		return "/admin/product";
	}
	//查询账单
	@RequestMapping("/queryFinance.do")
	public String list(UserPage userPage,ModelMap map,boolean goon){
		Page list = reportFormsService.list(userPage.getPageIndex(), userPage.getPageSize());
		List<ReportForms> list2 = (List<ReportForms>) list.getList();
		Map<Integer,Integer> map2 =new LinkedHashMap<>();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		double pay = 0;
		double income = 0;
		for(int i = 1;i <=12;i++){
		for (ReportForms goods : list2) {
				pay += goods.getPay();
				income += goods.getIncome();
				if (goods != null) {
					String format = formatter.format(goods.getTime());
					int indexOf = format.indexOf("-");
					String substring = format.substring(indexOf+1, indexOf+2);//2017-08-12--->0
					String substrings = format.substring(indexOf+1, indexOf+3);//2017-08-12--->08
					if (substring.equals("0")) {//判断是否为0
						String substring1 = format.substring(indexOf+2, indexOf+3);//8和i是否相等
						if (substring1.equals(String.valueOf(i))) {
							map2.put(goods.getId(),i);
						}
					}else{
						if (substrings.equals(String.valueOf(i))) {
							map2.put(goods.getId(),i);
						}
					}
//					System.out.println(map2.get(goods));
				}
			}
		}
		map.put("pay", Double.valueOf(String.format("%.2f", pay)));
		map.put("income",  Double.valueOf(String.format("%.2f", income)));
		map.put("list", list);
		if (goon) {
			map.put("map", map2);
			int counts = orderservice.counts();
			map.put("counts", counts);
			return "/admin/indexs";
		}
		return "/admin/finance";
	}
	
	// 根据订单状态查询
	@RequestMapping("/queryOrder.do")
	public String queryOrder(@RequestParam(value="orderStrup",required=false) OrderState orderStrup,ModelMap modelMap){
		try {
			List<Order> queryOrder = orderservice.queryOrder(orderStrup);
			if(queryOrder !=null){
				modelMap.put("queryList.list", queryOrder);
			}
			
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/admin/indent";
	}
	@RequestMapping("/addWage.htm")
	public String addWage(@ModelAttribute("wage")Wages wage){
		return "/admin/addWage";
	}
	@RequestMapping("/addWage.do")
	public String addWage(@Valid @ModelAttribute("wage")Wages wage,ModelMap modelMap){
		try {
			wage.setTime(new Timestamp(new Date().getTime()));
			reportFormsService.appendWage(wage);
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/admin.do";
	}
}
